<script setup lang="ts" name="PanelAsynchronous">
import { mapState } from 'pinia'
import { useModelerStore } from '@/store/bpmnProcess/modelerStore'
import { isAsynchronous, getACAfter, getACBefore, getACExclusive, setACAfter, setACBefore, setACExclusive } from '../../utils/asynchronous'
import EventEmitter from '@/utils/EventEmitter'

const form = ref({
  acBefore: false,
  acAfter: false,
  acExclusive: false
})

const mapStates = computed(() => {
  return mapState(useModelerStore, ['getActive'])
})

const showExclusive = computed(() => {
  return form.value.acBefore || form.value.acAfter
})

const updateElementAcBefore = (value) => {
  setACBefore(mapStates.value.getActive(), value)
  initData()
}

const updateElementAcAfter = (value) => {
  setACAfter(mapStates.value.getActive(), value)
  initData()
}

const updateElementAcExclusive = (value) => {
  setACExclusive(mapStates.value.getActive(), value)
  initData()
}

const initData = () => {
  form.value.acBefore = getACBefore(mapStates.value.getActive())
  form.value.acAfter = getACAfter(mapStates.value.getActive())
  form.value.acExclusive = getACExclusive(mapStates.value.getActive())
}

const eventEmitterListener = () => {
  if (isAsynchronous(mapStates.value.getActive())) {
    initData()
  }
}

onBeforeUnmount(() => {
  EventEmitter.removeListener('element-update', eventEmitterListener)
})

onMounted(() => {
  initData()
  EventEmitter.on('element-update', eventEmitterListener)
})
</script>

<template>
  <el-collapse-item name="asynchronous">
    <template #title>
      <div class="collapse-header">
        <svg-icon icon="ri:exchange-box-fill"></svg-icon>
        <h2>异步延续</h2>
      </div>
    </template>
    <el-form-item label="异步前">
      <el-switch v-model="form.acBefore" @change="updateElementAcBefore" />
    </el-form-item>
    <el-form-item label="异步后">
      <el-switch v-model="form.acAfter" @change="updateElementAcAfter" />
    </el-form-item>
    <el-form-item v-if="showExclusive" label="异步优先">
      <el-switch v-model="form.acExclusive" @change="updateElementAcExclusive" />
    </el-form-item>
  </el-collapse-item>
</template>

<style scoped lang="scss">
.el-collapse-item {
  :deep(.el-collapse-item__header) {

    .collapse-header {
      display: flex;
      flex: 1;
      align-items: center;
      padding: 0 12px;

      .el-icon {
        margin-right: 6px;
        font-size: 20px !important;
      }

      h2 {
        font-weight: bold;
        font-size: 14px;
      }
    }

    .el-icon {
      font-size: 18px;
    }
  }

  :deep(.el-collapse-item__content) {
    padding-right: 12px;
    padding-bottom: 12px;
    padding-left: 12px;
  }
}
</style>
